<?php

namespace App\Trip\Wechat\Pay;

use App\Models\Payment\ChannelPayment;
use App\Models\Payment\Payment;
use App\Models\Payment\Repositories\Interfaces\PaymentRepositoryInterface;
use Exception;

class PayConfig
{
    private array   $config;
    private Payment $defaultPayment;
    private mixed   $mchId;

    public function __construct(?array $config)
    {
        $this->setConfig($config);
    }

    /**
     * 支付配置发文件
     *
     * @return array
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * @throws Exception
     */
    public function setConfig($config): self
    {
        /**
         * @var PaymentRepositoryInterface $paymentRepo
         */
        $paymentRepo = app(PaymentRepositoryInterface::class);

        $mchid = $config['mchid'] ?? '';
        if (!$mchid && isset($config['appid'])) {
            $cp    = $config['appid'] ? (new ChannelPayment())->findOneByAppId($config['appid']) : null;
            $mchid = $cp?->getMchId() ?: '';
        }

        if (!$mchid) {
            throw new Exception("payment not found", 500);
        }

        $this->defaultPayment = $paymentRepo->findOnePaymentOrPayLog($mchid);
        $this->mchId          = $this->defaultPayment->getMchId();
        $this->config         = [
            'mch_id'         => $this->mchId,
            // 商户证书
            'private_key'    => $this->getFilePath("apiclient_key.pem"),
            'certificate'    => $this->getFilePath("apiclient_cert.pem"),
            // v3 API 秘钥
            'secret_key'     => $this->defaultPayment->getSecretKeyV3(),
            // v2 API 秘钥
            'v2_secret_key'  => $this->defaultPayment->getSecretKeyV2(),
            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                $this->getFilePath("wechatpay_v3.pem"),
            ],
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'           => [
                'timeout' => 5.0,
                'throw'   => false,
                //				'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];

        return $this;
    }

    public function getMchId(): string
    {
        return $this->mchId;
    }

    public function getCurrentPayment(): Payment
    {
        return $this->defaultPayment;
    }

    /**
     * @param string $file_name apiclient_key.pem apiclient_cert.pem wechatpay.pem
     *
     * @return string
     */
    private function getFilePath(string $file_name): string
    {
        return storage_path("certs/{$this->mchId}/{$file_name}");
    }
}